package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.RuleListMapper;
import com.indusfo.spc.mapper.RuleMapper;
import com.indusfo.spc.pojo.Rule;
import com.indusfo.spc.pojo.RuleList;
import com.indusfo.spc.service.RuleService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("ruleService")
public class RuleServiceImpl implements RuleService {

    private  static  final Logger logger = LoggerFactory.getLogger(RuleServiceImpl.class);

    @Resource
    private RuleMapper ruleMapper;

    @Resource
    private RuleListMapper ruleListMapper;

    /***
     * 新增
     * @param rule
     * @return
     */
    @Override
    public JSONObject insertRule(Rule rule) {
        try {
            if(rule.getRuleId()!= null){
                throw new ParamsErrorException("新增操作不能选择规则");
            }
            checkParam(rule);
            int row = ruleMapper.insertSelective(rule);
            if(row == 0 ){
                throw new ParamsErrorException("新增失败");
            }
            return JSONObject.oK("新增成功");
        }catch (GlobalException e){
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 删除
     *
     */
    @Transactional
    @Override
    public JSONObject delRule(Integer[] ids, Integer dataState){
        try {
            if( dataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if( dataState != 1 &&  dataState != 2 &&  dataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (ids == null) {
                throw new ParamsErrorException("请选择要删除的规则");
            }
            /**
             * @author: louk
             * @Description: 判断条码规则下是否含有条码信息
             * @date: 2019/9/6 14:20
             *
             */
            if(dataState==2){
                int countRuleList = ruleListMapper.listRuleListByRuleId(ids);
                if(countRuleList>0){
                    throw new ParamsErrorException("该规则下含有条码信息无法删除");
                }


            }
            // 执行存储过程
            int row = ruleMapper.delRule(ids,dataState);
            if(dataState==2  || row>0){
                for(Integer id :ids){
                    RuleList ruleList = new RuleList();
                    ruleList.setRuleId(id);
                    int row1 = ruleListMapper.delRuleListById(ruleList);
                }
            }
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch ( dataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch ( dataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        }catch  (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 更改
     *
     * @param rule
     */
    @Override
    public JSONObject updateRule(Rule rule) {
        try {
            if(rule.getRuleId() == null) {
                throw new ParamsErrorException("请选择要修改的规则");
            }
            checkParam(rule);

            int	row = ruleMapper.updateByPrimaryKeySelective(rule);

            if(row == 0) {
                throw new ModifyFailedException("数据更新失败！");
            }
            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }


    /**
     * 编码查重
     * @param ruleId
     * @param ruleCode
     * @return
     */
    @Override
    public Rule getByRuleCode(Integer ruleId, String ruleCode) {
        return ruleMapper.getByRuleCode(ruleId,ruleCode);
    }

    /**
     * 名称查重
     * @param ruleId
     * @param ruleName
     * @return
     */
    private Rule getByRuleName(Integer ruleId, String ruleName) {
        return ruleMapper.getByRuleName(ruleId,ruleName);
    }

    /**
     * 查询
     *
     * @param rule
     * @return
     */
    @Override
    public JSONObject queryRule(Rule rule) {
        List<Rule> liststRules = null;
        try {
            Integer pagesize = rule.getPagesize();
            Integer pageindex = rule.getPageindex();
            if(pagesize != null && pageindex != null) {
                rule.setIncept(pagesize*(pageindex - 1));
            }
            Integer ruleId = rule.getRuleId();
            if(ruleId != null) {  //如果有id,则查询单个
                liststRules = ruleMapper.getRule(ruleId);
            } else{  //查询多个
                liststRules = ruleMapper.listRule(rule);
            }
            if (liststRules.isEmpty()){
                return JSONObject.oK("没有相关数据", liststRules, 0);
            }
            //查询分页总记录数
            int count = ruleMapper.countRule(rule);
            return JSONObject.oK("查询成功", liststRules, count);

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 规则校验
     * @param rule
     */
    public void checkParam(Rule rule){
        if(StringUtils.isEmpty(rule.getRuleCode())){
            throw new ParamsErrorException("规则编码不能为空");
        }
        if (rule.getRuleCode().length() > 50) {
            throw new ParamsErrorException("规则编码字数超过规定,长度50");
        }
        if(StringUtils.isEmpty( rule.getRuleName())){
            throw new ParamsErrorException("规则名称不能为空");
        }
        if (rule.getRuleName().length() > 50) {
            throw new ParamsErrorException("规则名称字数超过规定,长度50");
        }
        if(getByRuleCode(rule.getRuleId(),rule.getRuleCode()) != null){
            throw new ParamsErrorException("规则编码已存在");
        }
        if(getByRuleName(rule.getRuleId(),rule.getRuleName()) != null){
            throw new ParamsErrorException("规则名称已存在");
        }
    }

}
